/// <reference path="../utilities/FXDom.js" />
/// <reference path="../utilities/Markup.js" />
/// <reference path="../utilities/Xpcom.js" />
///--------------------------------------------------------------------
/// <file name="QuickPM.js">
///   Provides enhancements for the PM screen that appears on most
///   pages.
/// </file>
///--------------------------------------------------------------------

NAMFox.ns(function() { with (NAMFox) {

this.QuickPM = function(_$, htmlDocument) {
    /// <summary>Initializes a new instance of the QuickPM class.</summary>
    /// <param name="_$" type="FXDom">
    ///   The FXDom selector that allows this QuickPM instance
    ///   to select DOM elements from the page itself.
    /// </param>
    /// <param name="htmlDocument" type="Document">
    ///   The HTML Document object for the current page.
    /// </param>
    /// <param name="forumId" type="Number">
    ///   The ID of the forum to which Quick Caption is being added.
    /// </param>
    
    this._$ = _$;
    this._htmlDocument = htmlDocument;
};

QuickPM.prototype = {
    _onDomNodeInserted: function(event, htmlDocument, _$) {
        var newNode = event.target;

        // The node that was inserted.
        $.verbose("Global PM | Target: " + newNode + " # " + newNode.id + " . " + newNode.className);

        // The parent of the target.
        $.verbose("Global PM | Related: " + event.relatedNode + " # " + event.relatedNode.id + " . " + event.relatedNode.className);

        if (!$FX.nodeName(newNode, "form")) {
            return;
        }

        $.verbose("Global PM | New node of interest detected.");
    
        var form = null;
        var results = null;
        if (results = newNode.id.match(/^postingform_\d+$/)) {
            $.verbose("Global PM | Found existing conversation.");
            form = _$(newNode);
        }
        else if (newNode.id === "postingform") {
            $.verbose("Global PM | New PM detected.");
            form = _$(newNode);
        }

        if (form && !form.find("select[name=namfox-custom-messages-select]").length) {
            // Update the PM preference checkboxes.
            form.find("input[name=read_rcpt]").attr("checked", $.getConfig().privateMessages.readReceipt);

            // Attach AutoComplete and the default message to the textarea.
            var textArea = form.find("textarea[name=message]");
            textArea.val($.messages.getDefaultMessage().text);
            htmlDocument.__namfox__.autoComplete.attachSingle(textArea);

            textArea.parent().after(
                _$("<p>").append(
                    Markup.create(
                        textArea,
                        MarkupLocation.QuickPM,
                        Markup.customMessages
                    )
                )
            );
        }
    },

    attach: function() {
        /// <summary>Attaches enhancements for the global PM screen to this page.</summary>
            
        $.verbose("Global PM | Attaching enhancements to the global PM.");

        // DOM change events are flagged as deprecated but there is no other event listed to get what
        // we need. We need to listen to these events in order to tell when script on the web site
        // adds new elements, so we can add NAMFox's enhancements to those elements.
        this._$("#send_pm_form").get(0).addEventListener(
            "DOMNodeInserted",
            $.createCallback(this._onDomNodeInserted, this, this._htmlDocument, this._$),
            false);

        this._$("body").get(0).addEventListener(
            "DOMNodeInserted",
            $.createCallback(this._onDomNodeInserted, this, this._htmlDocument, this._$),
            false);

        // Used to supply the default message for the PM window. By default
        // we can't listen for the text area to be added to the form, because
        // Neoseeker automatically resets the text area's value to "".
        var replacementScript = '';
        replacementScript += 'var original_show_pm_form = window.show_pm_form;';
        replacementScript += 'window.show_pm_form = function() {';
        replacementScript += '    if (!arguments[2]) {';
        replacementScript += '        arguments[2] = "' + $.attrEncode($.messages.getDefaultMessage().text) + '";';
        replacementScript += '    }';
        replacementScript += '';
        replacementScript += '    original_show_pm_form.apply(window, arguments);';
        replacementScript += '};';

        Sandbox.evalOnPage(
            this._htmlDocument,
            replacementScript);
    }
};

}});